﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using mshtml;
using SHDocVw;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace AutomatizzazioneCleverConsumit
{
    class Automation
    {
        [DllImport("user32.dll", SetLastError = true)]
        static extern Int32 FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        WebUtil _wu = null;
        WebClient wc;
        string cookies = "";

        /// <summary>
        /// 
        /// </summary>
        /// <returns> return OK ifeverything worked else the error message </returns>

        public void WaitPageUntillComplete(InternetExplorer ie)
        {
            while (ie.ReadyState.ToString() != "READYSTATE_COMPLETE")
            {
                Thread.Sleep(3000);
            }
        }

        public string Login(string user, string pwd)
        {
            string output = "OK";

            //first we init the Ie object
            _wu = new WebUtil();
            //then we login and go to
            string website = ConfigUtil.GetWebSite();

            _wu.Navigate(website, 1);
            output = _wu.SetInputStringValue("input", "id", "username", user);
            if (output == "OK") 
            {
                output = _wu.SetInputStringValue("input", "id", "password", pwd);
                if (output == "OK")
                {
                    output = _wu.ClickButton("input", "value", "LOGIN");
                    if (output == "OK")
                    {
                        WaitPageUntillComplete(_wu.IE);
                    }
                    else
                    {
                        output = "Error at pressing submit button - login";
                    }
                }
                else
                {
                    output = "Error at inserting password";
                }
            }
            else
            {
                output = "WebPage not available!";
            }

            return output;
        }

        public string MonitoraggioLotti()
        {
            string output = "OK";
            try
            {
                _wu.Navigate("https://recupero.consum.it/collection-web/soaSearchMonitor.action?task=list&reset=true", 1);
            }
            catch
            {
                output = "Error at navigate to Monitoraggio Lotti";
            }
            return output;
        }

        public string DoWork()
        {
            string output = "OK";
            string lamp = "/collection-web/images/green/lamp.png";
                 //"/collection-web/images/green/readyForPreClosure.png"; //test

            IHTMLElement lottiTable = null;

            HTMLDocument docIE = (HTMLDocument)_wu.IE.Document;

            IHTMLElementCollection tdCol = docIE.getElementsByTagName("td");
            foreach (IHTMLElement tdElem in tdCol)
            {
                if (tdElem.innerText != null)
                {
                    if (tdElem.innerText == "ID LOTTO")
                    {
                        lottiTable = tdElem.parentElement.parentElement;
                        break;
                    }
                }
            }

            if (lottiTable == null)
            {
                output = "Error - Cannot find Lotti Table";
                return output;
            }

            string data = "";
            int lampElements = 0;
            IHTMLElementCollection trElemCol = docIE.getElementsByTagName("tr");
            try
            {
                foreach (IHTMLElement rightTR in trElemCol)
                {
                    if (
                        rightTR.innerHTML.Contains(lamp) && 
                        rightTR.parentElement == lottiTable)
                    {
                        string trString = rightTR.innerHTML;
                        string[] tdElems = Regex.Split(trString, "</TD>");
                        data = tdElems[3];
                        data = data.Substring(data.IndexOf('>') + 1, 10);
                        data = data.Replace('/', '-');
                        output = DoWorkForTR(rightTR, data);
                        lampElements++;
                        if (output == "OK")
                        {
                            //return output;
                        }
                        else
                        {
                            output = "Error - processing TR fail";
                            return output;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log(ex.StackTrace + "\n " + ex.ToString(), LogType.Exceptie);
            }

            if (lampElements > 0)
            {
                DateTime now = DateTime.Now;
                string subject = "AGGIORNAMENTO CONSUMIT PHONE DEL " + now.Year.ToString() + "-" + now.Month.ToString() + "-" + now.Day.ToString();
                string body = "Si prega di procedere con la lavorazione del file prelevato e salvato nel seguente percorso: ";
                body += ConfigUtil.GetOutput() + @"\";
                body += now.Year + "-" + now.Month + "-" + now.Day + @"\";
                MailUtils.SendMsg(subject, body);
            }
            else
            {
                // send mail fara update-uri
                string subject = "NESSUN AGGIORNAMENTO CONSUMIT PHONE TROVATO.";
                string body = "";
                MailUtils.SendMsg(subject, body);
            }

            return output;
        }

        public string DoWorkForTR(IHTMLElement lampTR, string data)
        {
            string output = "OK";
            string amministrazioneImg = "/collection-web/images/green/menu_amministrazione.gif";
            string downloadImg = "/collection-web/images/green/downloadAssignmentFileBlue.gif";

            HTMLDocument docIE = (HTMLDocument)_wu.IE.Document;

            IHTMLElementCollection imgElemCol = docIE.getElementsByTagName("img");

            try
            {
                // click Azione image -> js generated menu will appear
                foreach (IHTMLElement rightIMG in imgElemCol)
                {
                    if (rightIMG.outerHTML.Contains(amministrazioneImg))
                    {
                        if (rightIMG.parentElement.parentElement == lampTR)
                        {
                            rightIMG.click();
                            break;
                        }
                    }
                }


                //from the menu click on the first item
                foreach (IHTMLElement dlImg in imgElemCol)
                {
                    if (dlImg.outerHTML.Contains(downloadImg))
                    {
                        if (dlImg.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement == lampTR)
                        {
                            dlImg.click();
                            break;
                        }
                    }
                }

                //search download file
                WaitPageUntillComplete(_wu.IE); 
                Thread.Sleep(3000);

                //we are now on the generated page from the id of the selected row !!
                //https://recupero.consum.it/collection-web/soaSearchMonitor.action?task=downloadUpdateFileOld&soaId=FB14BE50-04B1-11E3-BA9E-005056B800C0&fileId=C6AF53B0-1748-11E3-89B6-005056B800CC
                docIE = (HTMLDocument)_wu.IE.Document;

                IHTMLFramesCollection2 frames = (IHTMLFramesCollection2)docIE.frames;
                object o = null;
                for (int i = 0; i < frames.length; i++)
                {
                    o = i;
                    int ok = 0;
                    IHTMLWindow2 fr = (IHTMLWindow2)frames.item(ref o);
                    HTMLDocument doc = (HTMLDocument)fr.document;

                    IHTMLElement dlTable = null;

                    IHTMLElementCollection tdCol = doc.getElementsByTagName("td");
                    //search the table container then the actual image mapped to the link and click
                    foreach (IHTMLElement tdElem in tdCol)
                    {
                        if (tdElem.innerText != null)
                        {
                            if (tdElem.innerText == "NUOVO FILE DI AGGIORNAMENTO DA SCARICARE  ")
                               // "ALTRI FILE DI AGGIORNAMENTO  ")
                            {
                                dlTable = tdElem.parentElement.parentElement;
                                break;
                            }
                        }
                    }
                    // first download image
                    imgElemCol = doc.getElementsByTagName("img");
                    foreach (IHTMLElement imgElem in imgElemCol)
                    {
                        if (imgElem.outerHTML.Contains(downloadImg) && imgElem.parentElement.parentElement.parentElement.parentElement == dlTable)
                        {
                            HTMLAnchorElement anchor = imgElem.parentElement as HTMLAnchorElement;
                            if (anchor != null)
                            {
                                Logger.Log("File LINK - " + anchor.href, LogType.File);
                                ok = 1; //only first anchor
                                Thread.Sleep(3000);
                                SaveFile(data,anchor);
                                break;
                            }
                            else
                            {
                                output = "Error at finding href anchor of the file.";
                            }
                        }
                    }
                    if (ok == 1)
                    {
                        break;
                    }
                }
            }
            catch
            {
                output = "Error - at <tr> element processing";
                Logger.Log(output, LogType.Exceptie);
                return output;
            }

            return output;
        }

        private  void SaveFile(string data,HTMLAnchorElement anchor)
        {
            string path = ConfigUtil.GetOutput() + @"\";
            DateTime now = DateTime.Now;
            path = path + now.Year + "-" + now.Month + "-" + now.Day;
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            Logger.Log("Download file at path: " + path, LogType.File);
            wc = new WebClient();
            wc.Headers.Add(HttpRequestHeader.Cookie, cookies);
            
            wc.DownloadFile(anchor.href, path + @"\" + data + "_");
            string fileName = wc.ResponseHeaders["content-disposition"].Split(';')[1].Split('=')[1];
            if (File.Exists(path + @"\" + data + "_"))
            {
                File.Move(path + @"\" + data + "_",path + @"\" + data + "_" +fileName);
            }
           // SendKeys.SendWait(path + @"\" + data + "_");
        }

        public void ProcessAll(string user, string pwd)
        {
            string check = "";

            //Login will return Ok message if all went ok or a fail message 
            check = Login(user, pwd);
            mshtml.HTMLDocument testDoc = _wu.IE.Document as mshtml.HTMLDocument;
            
            if (testDoc != null)
            {
                 cookies = testDoc.cookie;
            }
            
            if (check != "OK")
            {
                Logger.Log(check, LogType.Error);
                _wu.ClosePage();
                ErrorMail();
                return;
            }

            //Navigate to Minitoraggio Lotti
            check = MonitoraggioLotti();
            if (check != "OK")
            {
                Logger.Log(check, LogType.Error);
                _wu.ClosePage();
                ErrorMail();
                return;
            }

            //Run all steps
            check = DoWork();
            if (check == "OK")
            {
                _wu.ClosePage();
            }
            else
            {
                Logger.Log(check, LogType.Error);
                _wu.ClosePage();
                ErrorMail();
            }
        }

        public void ErrorMail()
        {
           MailUtils.SendMsg("ERRORE PRELEVAMENTO CONSUMIT PHONE", "");
        }
    }
}
